<template>
  <div class="app-container">
    <div class="filter-container">
    <el-row>
      <el-col :span="22">
          <el-radio-group v-model="filterForm.status" @input="handleFilter">
            <el-radio-button label="0">所有</el-radio-button>
            <el-radio-button label="2">已平仓</el-radio-button>
            <el-radio-button label="1">持仓</el-radio-button>
          </el-radio-group>
          <el-radio-group v-model="filterForm.simulation" @input="handleFilter">
            <el-radio :label="2">真实</el-radio>
            <el-radio :label="1">模拟</el-radio>
          </el-radio-group>
      </el-col>
      <el-col :span="2">
          <el-button @click="handleFilter()">搜索</el-button>
      </el-col>
    </el-row>
      </div>
    <el-row>
  <el-col :span="20">
    
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      stripe
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="合约" width="350px">
          <template slot-scope="{row}">
            <span @click="handleMarket(row)">{{ row.symbol }}<el-tag>{{ row.status.label }}</el-tag></span>
          </template>
      </el-table-column>
      <el-table-column label="价格" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="市场价" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.marketPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="浮动盈亏" min-width="150px">
        <template slot-scope="{row}">
          <span>{{row.marketWeight}}%<el-tag v-if="row.profit < 0" effect="dark" type="success">{{ row.profit }}</el-tag><el-tag effect="dark" type="danger" v-else >{{ row.profit }}</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.quantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开仓日期" min-width="180px">
        <template slot-scope="{row}">
          <span>{{ row.createdAt }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期日期" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.expireDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="平仓价格" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.closingPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="识别码" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.magic }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" v-if="row.status.value == 1" @click="handleModifyStatus(row,2)">
            平仓
          </el-button>
          <el-button size="mini" v-if="row.status.value == 2" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filterForm.page" :limit.sync="filterForm.size" @pagination="getList" />

  </el-col>
  <el-col :span="4">
    <div style="padding:0 15px;">
        <el-card shadow="always">
          <div slot="header" class="clearfix">
            <span>常见操作</span>
          </div>
      <el-button @click="onPurchaseHiddenOpen()">开仓</el-button>
      <br />
      <el-button @click="onShipmentsList()">平仓</el-button>
      <br />
      <el-button @click="onAuthorizeList()">委托</el-button>
      <br />
      <el-button @click="onDeliveryList()">流水</el-button>
      <br />
      <el-button @click="onPurchaseClean()">清仓</el-button>
      <br />
      <el-button @click="onCalculatorOpen()">保证金计算器</el-button>
         </el-card>

    </div>

  </el-col>
</el-row>

    <el-dialog
      title="开仓"
      :visible.sync="purchaseHiddenOpen"
      :close-on-click-modal="false"
      width="30%">
      <el-form ref="filterForm" :model="purchaseForm"  label-position="left" label-width="100px">
        <el-form-item label="合约" prop="symbol">
          <el-input v-model="purchaseForm.symbol" clearable placeholder="合约" style="width: 200px;" class="filter-item"/>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="purchaseForm.price" placeholder="价格" @input="handlePurchasePriceListen" style="width: 200px;" class="filter-item" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="purchaseForm.quantity" @change="handlePurchaseQuantityListen" :min="1" :max="10" label="数量"></el-input-number>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="purchaseForm.amount"  readonly="readonly" placeholder="金额" />
        </el-form-item>
        <el-form-item label="手续费" prop="cost">
          <el-input v-model="purchaseForm.cost"  readonly="readonly" placeholder="手续费" />
        </el-form-item>
        <el-form-item label="总额" prop="capital">
          <el-input v-model="purchaseForm.capital" readonly="readonly" placeholder="总额" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="purchaseHiddenOpen = false">取 消</el-button>
        <el-button type="primary" @click="handlePurchaseSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="保证金计算器"
      :visible.sync="hiddenCalculator"
      :close-on-click-modal="false"
      width="50%">
      <el-form ref="filterForm" :model="symbolForm"  label-position="left" label-width="100px">
        <el-form-item label="经纪商" prop="brokerID">
           <el-select v-model="symbolForm.brokerID" placeholder="请选择">
            <el-option
              v-for="broker in brokerOptions"
              :key="broker.ID"
              :label="broker.brokerName"
              :value="broker.ID">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合约" prop="symbol">
           <el-select v-model="symbolForm.symbolType" placeholder="请选择">
            <el-option
              v-for="broker in symbolTypeOptions"
              :key="broker.value"
              :label="broker.label"
              :value="broker.value">
            </el-option>
          </el-select>
           <el-select v-model="symbolForm.symbolName" placeholder="请选择">
            <el-option
              v-for="broker in symbolOptions"
              :key="broker.ID"
              :label="broker.brokerName"
              :value="broker.ID">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市场价" prop="marketPrice">
          <el-input v-model="symbolForm.marketPrice" placeholder="市场价" @input="handleCalculatorPriceListen" style="width: 200px;" class="filter-item" />
        </el-form-item>
        <el-form-item label="保证金" prop="margin">
          <div>{{symbolForm.margin}}%</div>
        </el-form-item>
        <el-form-item label="手续费" prop="amount">
          <el-input v-model="symbolForm.amount"  readonly="readonly" placeholder="手续费" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="hiddenCalculator = false">取 消</el-button>
        <el-button type="primary" @click="handlePurchaseSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//import { getFaultinessList,  removeFaultinessByID, changeFaultinessStatusByID } from '@/api/development/faultiness'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import {getHost} from '@/utils/socket' // secondary package based on el-pagination
import {getSymbol} from '@/utils/symbol' // secondary package based on el-pagination
import {getInventoryList} from '@/api/position/inventory'

export default {
  name: 'financeDashboard',
  components: { Pagination },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      
      socket:"",
      tableKey: 0,
      list: null,
      windowHeight:"800",
      hiddenCalculator:false,
      brokerOptions:[],
      symbolTypeOptions:[
        {
          label:"期货",
          value:1
        },
        {
          label:"期权",
          value:2
        }
      ],
      symbolOptions:[
      ],
      symbolForm:{
        brokerID:undefined,
        marketPrice:0
      },
      total: 0,
      listLoading: false,
      purchaseForm:{
        quantity:1,
        price:0,
        symbol:""
      },
      purchaseHiddenOpen:false,
      connected:"loading",
      filterForm: {
        page: 1,
        size: 10,
        simulation:2,
        symbol:"",
        status:1,
        sort: '+id'
      }
    }
  },
  created() {
    let symbolData = getSymbol()
    try {
      this.filterForm.localSymbol = symbolData.code
    } catch (error) {
      
    }
    this.getList()
  },
  destroyed () {
  },
  methods: {
    onCalculatorOpen:function(){
      this.hiddenCalculator = true
    },
    onCalculatorClose:function(){
      
    },
    handleCalculatorPriceListen:function(){
      
    },
    handlePurchaseQuantityListen:function(quantity){
      console.log(quantity)
      let accountCostWeight = 0.0003
      let accountMargin = 0.2
      let symbolWeight = 20
      this.purchaseForm.cost = quantity*this.purchaseForm.price*accountCostWeight;
      this.purchaseForm.amount = quantity*this.purchaseForm.price*symbolWeight*accountMargin;
      this.purchaseForm.capital = this.purchaseForm.cost+this.purchaseForm.amount;
      this.purchaseForm.capital = Number(this.purchaseForm.capital).toFixed(2)
      this.purchaseForm.cost = Number(this.purchaseForm.cost).toFixed(2)
    },
    handlePurchasePriceListen:function(){
      let accountCostWeight = 0.0003
      let accountMargin = 0.2
      let symbolWeight = 20
      let quantity = this.purchaseForm.quantity
      this.purchaseForm.cost = quantity*this.purchaseForm.price*accountCostWeight;
      this.purchaseForm.amount = quantity*this.purchaseForm.price*symbolWeight*accountMargin;
      this.purchaseForm.capital = this.purchaseForm.cost+this.purchaseForm.amount;
      this.purchaseForm.capital = Number(this.purchaseForm.capital).toFixed(2)
      this.purchaseForm.cost = Number(this.purchaseForm.cost).toFixed(2)
    },
    handleMarket:function(item){
      this.$router.push({ path:'/policy/policy', query: {"symbol":item.symbol} })
    },
    handlePurchaseSubmit:function(){
      this.send({
        "conversationType":"position.purchase.open",
        "message":this.purchaseForm,
        "target":{"id":"3"}
      })

    },
    getList:function(){
      let _this = this;
      console.log("期权",_this.filterForm)
      getInventoryList(_this.filterForm).then((response) => {
        console.log("getList",response)
          if (response.code === 200) {
            this.total = response.data.total
            _this.list = [];
            console.log(response.data.total)
            response.data.list.forEach((data,index)=>{
              data['marketWeight'] = (data['marketPrice']-data['price'])/data['price']*100
              data['marketWeight'] = data['marketWeight'].toFixed(2)
              _this.list.push(data)
            })
            this.total = response.data.total
          } else {
            _this.$message({
              message: response.msg,
              type: 'error'
            })
          }
      })
    },
    onShipmentsList:function(){
      this.$router.push({ path: "shipments" })
    },
    onAuthorizeList:function(){
      this.$router.push({ path: "authorize" })
    },
    onDeliveryList:function(){
      this.$router.push({ path: "delivery" })
    },
    handleDelete:function(row){
      let _this = this;
      this.$confirm('此操作将清空所有持仓合约, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.send({
            "conversationType":"position.purchase.delete",
            "message":{"purchaseID":row.ID,"localSymbol":_this.filterForm.localSymbol},
            "target":{"id":"3"}
          })
      }).catch(() => {
      });
    },
    onPurchaseClean:function(){
      let _this = this;
      this.$confirm('此操作将清空所有持仓合约, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.send({
            "conversationType":"position.purchase.clean",
            "message":{"page":this.filterForm.start,"size":this.filterForm.perpage},
            "target":{"id":"3"}
          })
      }).catch(() => {
      });
    },
    onPurchaseHiddenOpen:function(){
      this.purchaseHiddenOpen = true
    },
    handleFilter() {
      this.filterForm.page = 1
      console.log(this.filterForm)
      this.getList()
    },
    sortChange:function(){

    }
  }
}
</script>
<style>

</style>